package com.wwj.utils;

import com.alibaba.fastjson.JSONPath;
import com.wwj.Constant.Constant;
import org.apache.http.client.methods.HttpRequestBase;

import java.util.HashMap;
import java.util.Map;

public class AuthenticationUtils {

    //环境变量
    public static Map<String,String> env = new HashMap<String,String>();

    public static void main(String[] args) {
//        HttpUtils.testPostjson("","");
        String s = "{\n" +
                "    \"code\": 0,\n" +
                "    \"msg\": \"OK\",\n" +
                "    \"data\": {\n" +
                "        \"id\": 17021,\n" +
                "        \"leave_amount\": 10,\n" +
                "        \"mobile_phone\": \"18311447530\",\n" +
                "        \"reg_name\": \"小太阳\",\n" +
                "        \"reg_time\": \"2020-06-15 11:05:33.0\",\n" +
                "        \"type\": 1,\n" +
                "        \"token_info\": {\n" +
                "            \"token_type\": \"Bearer\",\n" +
                "            \"expires_in\": \"2020-06-15 19:45:28\",\n" +
                "            \"token\": \"eyJhbGciOiJIUzUxMiJ9.eyJtZW1iZXJfaWQiOjE3MDIxLCJleHAiOjE1OTIyMjE1Mjh9.9DJ9f4GMxZWJ4bsdp9iXzXASJYQH5gDsmKIicakhy7HdQifis1Zw05165m3Yop5mFDnmyUhHtBtnUcDb46-rIQ\"\n" +
                "        }\n" +
                "    },\n" +
                "    \"copyright\": \"Copyright 柠檬班 © 2017-2020 湖南省零檬信息技术有限公司 All Rights Reserved\"\n" +
                "}";

        storeToken(s);


    }

    /**从响应体中获取token
     * @param responseBody
     */
    public static void storeToken(String responseBody){
        //1.取出token
        Object token = JSONPath.read(responseBody,"$.data.token_info.token");
        //2.存储,不为空时存贮
         if(token!=null){
             env.put("token",token.toString());
             //3.获取并存储member_id
             Object member_id = JSONPath.read(responseBody,"$.data.id");
             if(member_id!=null){
                 env.put(Constant.MEMBER_ID,member_id.toString());

             }
         }

    }
    /**添加token到请求头
     * @param request
     */
    public static void addToken(HttpRequestBase request){
        System.out.println("开始调用添加鉴权。。");

        String token = env.get("token");
        if(token!=null){
            request.addHeader("Authorization","Bearer "+token);
            System.out.println("已经添加token1:"+token);
        }
        System.out.println("已经添加token2:"+token);

    }

}
